package com.example.stock.util;

import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;

public class DateUtil {

    static SimpleDateFormat dailyFormat = new SimpleDateFormat("yyyy-MM-dd");

    public static String dateDailyFormat(Date date) {
        return dailyFormat.format(date);
    }

    public static String dateWeekFormat(String dateString) {
        // 创建一个DateTimeFormatter对象，用于定义日期字符串的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

        // 使用LocalDate.parse方法和DateTimeFormatter对象将字符串解析为LocalDate对象
        LocalDate parseDate = LocalDate.parse(dateString, formatter);

        LocalDate monday = parseDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate sunday = parseDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));

        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("MMdd");
        return parseDate.getYear() + ":" + monday.format(pattern)  + "--" + sunday.format(pattern);
    }

    public static int calWeekDataDuration(String now, String past) {
        return  52 * (Integer.parseInt(now.substring(0,4)) - Integer.parseInt(past.substring(0,4))) + (
                Integer.parseInt(now.substring(6,8)) - Integer.parseInt(past.substring(6,8))
                );
    }

    private static final DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy/M/d");

    private static final DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    /**
     * 将字符串格式 "2025/1/1" 转换为 "2025-01-01"
     * @param date
     * @return
     */
    public static String reFormatDate(String date) {
        // 解析为 LocalDate 对象
        LocalDate localDate = LocalDate.parse(date, inputFormatter);
        // 格式化输出
        return localDate.format(outputFormatter);
    }
}
